package com.cg.service.impl;

import com.cg.dao.UserMapper;
import com.cg.entity.User;
import com.cg.service.UserService;
import com.cg.service.UserTokenService;
import com.cg.util.MD5Utils;
import com.cg.vo.LoginUserVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.UUID;

/**
 * (User)表服务实现类
 *
 * @author chengong
 * @since 2024-01-14 18:06:01
 */
@Service("userService")
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;

    @Resource
    private UserTokenService userTokenService;

    /**
     * 添加新用户
     */
    @Override
    public Integer createUser(User user) {
        Integer count =0;
        try {
            //codeNum是随机生成的
            String codeNum = this.createCode();
            //密码加盐加密处理
            //获取随机生成的盐
            String salt = MD5Utils.getSalt();
            //获取用户输入的密码
            String password = user.getPassword();
            password = MD5Utils.saltMD5(salt,password);
            user.setPassword(password);
            user.setCodeNum(codeNum);
            user.setSlat(salt);
            count = userMapper.createUser(user);
        }catch (Exception e){
            e.printStackTrace();
        }
        return count;
    }

    /**
     * 用UUID生成随机的code
     */
    @Override
    public String createCode() {
        String codeNum = UUID.randomUUID().toString().replace("-", "");
        return codeNum;
    }

    /**
     * 用户登录
     */
    @Override
    public LoginUserVo login(User user) {
        LoginUserVo loginUserVo = userMapper.login(user);
        if(loginUserVo == null){
            return null;
        }
        //验证密码
        //获取盐
        String slat = loginUserVo.getSlat();
        //数据库里面的密码
        String passwordSQL = loginUserVo.getPassword();
        String password = user.getPassword();
        password = MD5Utils.saltMD5(slat,password);
        if(!password.equals(passwordSQL)){//两个MD5格式密码进行比较
            return null;
        }
        //保存到redis中
        //安全起见，显示的密码赋空值
        loginUserVo.setPassword("");
        userTokenService.setUserToken(loginUserVo);

        return loginUserVo;
    }
}
